package com.xian.im.web.modules.sys;

import com.xian.im.common.constant.EhcacheConstant;
import com.xian.im.common.result.RestResult;
import com.xian.im.common.result.RestResultBuilder;
import com.xian.im.config.RedisHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-02-03 10:21
 **/
@Slf4j
@RestController
@RequestMapping("im/cache")
@Api(value = "缓存管理", tags = {"缓存管理"})
public class SystemCacheController {

    @Autowired
    private RedisHelper redisHelper;

    @Autowired
    private RedisTemplate redisTemplate;
    
    @ApiOperation(value = "清理指定缓存组", notes = "清理指定缓存组")
    @RequestMapping(value = "clear/{cacheName}",method = RequestMethod.GET)
    public RestResult<Boolean> clear(@PathVariable("cacheName") String cacheName){
        List<String> keys = redisHelper.keys(RedisHelper.CACHE_REDIS_PREFIX+cacheName + "*");
        redisTemplate.delete(keys);
        log.info("清理指定缓存组 keys {}",keys);
        return RestResultBuilder.builder().success(true).build();
    }

    @ApiOperation(value = "获取缓存分组集合", notes = "获取缓存分组集合")
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public RestResult<Set<String>> list(){
        Set<String> keys = new HashSet<>();
        for (EhcacheConstant value : EhcacheConstant.values()) {
          keys.add(value.getName());
        }
        return RestResultBuilder.builder().success(keys).build();
    }
}
